package com.ruoyi.kafka;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.lock.domain.ABuildHome;
import com.ruoyi.lock.mapper.ABuildHomeMapper;
import com.ruoyi.lock.mapper.AHomeUserMapper;
import com.ruoyi.lock.mapper.ATenantkeyMapper;
import com.ruoyi.locksApi.service.IRemoteOpenService;
import com.ruoyi.locksApi.service.LockApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@ConditionalOnProperty(value = "spring.profiles.active", havingValue = "druid", matchIfMissing = false)
public class refundKafkaListener {
    @Autowired
    private ATenantkeyMapper aTenantkeyMapper;
    @Autowired
    private AHomeUserMapper aHomeUserMapper;
    @Autowired
    private ABuildHomeMapper aBuildHomeMapper;
    @Autowired
    private LockApiService lockApiService;
    @Autowired
    private IRemoteOpenService remoteOpenService;
    public refundKafkaListener() {
        log.info("refundKafkaListener 类已被加载和实例化");
    }

    /**
     * 监听连山云消耗数据
     *
     * @param ack 手动ack
     */
    @KafkaListener(topics = "liuzhong", groupId = "1", properties = {
            "max.poll.records=1",
            "auto.offset.reset=earliest",
            "max.poll.interval.ms=10000"}, containerFactory = "singleListenerContainerFactory")
    public void lianshanRealtimeListener(ConsumerRecord<String, String> record, Acknowledgment ack) {
        // 获取分区编号
        int partition = record.partition();
        long offset = record.offset();
        log.info("分区编号：{}偏移量是：{}", partition, offset);
        Map<String, Object> socketDataMap = new HashMap<>();

        JSONObject json = JSON.parseObject(record.value()).getJSONObject("body");

        // 业务处理：如果method=lockLogPush且logType=8，提取keyId和lockKeyId
        try {
//            com.alibaba.fastjson.JSONObject json = body != null ? com.alibaba.fastjson.JSONObject.parseObject(body) : null;
            if (json != null && "lockLogPush".equals(json.getString("method"))) {
                JSONObject data = json.getJSONObject("data");
                // 新增：处理删除操作 logType=9
                if (data != null && data.getIntValue("logType") == 9) {
                    JSONArray logKeys = data.getJSONArray("logKeys");
                    if (logKeys != null && logKeys.size() > 0) {
//                        JSONObject keyObj = logKeys.getJSONObject(1);
//                        String lockKeyId = keyObj.getString("lockKeyId");
                        //删除钥匙
//                        if (lockKeyId != null) {
//                            log.info("logType=9, 删除lockKeyId={}", lockKeyId);
//                            log.info("删除钥匙详情: {}", JSONObject.toJSONString(keyObj, SerializerFeature.PrettyFormat));
//                            aTenantkeyMapper.deleteByLockKeyId(lockKeyId);
//                            //房间退租
//                        } else {
//                            String lockUserId = keyObj.getString("lockUserId");
//                            if (lockUserId != null) {
//                                log.info("logType=9, 退租lockUserId={}", lockUserId);
//                                log.info("退租详情: {}", JSONObject.toJSONString(keyObj, SerializerFeature.PrettyFormat));
//                                aTenantkeyMapper.deleteByLockUserId(lockUserId);
//                                // keyGroupId 置空
//                                aHomeUserMapper.clearKeyGroupIdByKeyGroupId(lockUserId);
//                            }
//                        }
                    }
                }
                // 原有：添加操作 logType=8
                if (data != null && data.getIntValue("logType") == 8) {
                    String roomId = data.getString("roomId");


                    JSONArray logKeys = data.getJSONArray("logKeys");
                    if (logKeys != null && logKeys.size() > 1) {
                        JSONObject keyObj = logKeys.getJSONObject(1);
                        String keyId = keyObj.getString("keyId");
                        String lockKeyId = keyObj.getString("lockKeyId");
                        if (keyId != null && lockKeyId != null) {
                            log.info("logType=8, keyId={}, lockKeyId={}", keyId, lockKeyId);
                            log.info("添加钥匙详情: {}", JSONObject.toJSONString(keyObj));
                            ABuildHome aBuildHome = aBuildHomeMapper.selectABuildHomeByRoomNum(roomId);
                            // 更新数据库
                            aTenantkeyMapper.updateLockKeyIdByPwdId(keyId, lockKeyId,aBuildHome.getId());
                        }
                    }
                }
                // 新增：处理门锁心跳 logType=33
                if (data != null && data.getIntValue("logType") == 33) {
                    String roomId = data.getString("roomId");
                    Integer electricNum = data.getInteger("electricNum");
                    if (roomId != null && electricNum != null) {
                        log.info("logType=33, 心跳上报 roomId={}, 电量={}", roomId, electricNum);
                        log.info("心跳详情: {}", com.alibaba.fastjson.JSONObject.toJSONString(data));
                        aBuildHomeMapper.updateLastCommunicationAndBatteryByRoomId(roomId, electricNum);

                        // 检查房间的 lock_state 是否为 1，如果是则自动调用远程开门
                        try {
                            log.info("开始检查房间 {} 的 lock_state", roomId);

                            // 查询房间信息，检查 lock_state
                            ABuildHome roomInfo = aBuildHomeMapper.selectABuildHomeByRoomNum(roomId);
                            log.info("查询房间信息结果: {}", roomInfo != null ? com.alibaba.fastjson.JSONObject.toJSONString(roomInfo) : "null");

                            if (roomInfo != null) {
                                log.info("房间 {} 的 lockState 值: {}", roomId, roomInfo.getLockState());
                                log.info("房间 {} 的 roomNum 值: {}", roomId, roomInfo.getRoomNum());
                                log.info("房间 {} 的 roomName 值: {}", roomId, roomInfo.getRoomName());
                                log.info("房间 {} 的 id 值: {}", roomId, roomInfo.getId());

                                if (roomInfo.getLockState() != null && roomInfo.getLockState() == 1L) {
                                    log.info("检测到房间 {} 的 lock_state 为 1，自动调用远程开门", roomId);

                                    // 构建远程开门参数
                                    Map<String, Object> openParams = new HashMap<>();
                                    openParams.put("roomNum", roomId);
                                    log.info("远程开门参数: {}", com.alibaba.fastjson.JSONObject.toJSONString(openParams));

                                    // 调用远程开门
                                    com.alibaba.fastjson.JSONObject openResult = remoteOpenService.apartmentOpenDoorLock(openParams);
                                    log.info("自动远程开门结果: {}", com.alibaba.fastjson.JSONObject.toJSONString(openResult));

                                    // 无论开门成功与否，都将 lock_state 改为 0
                                    int updateResult = aBuildHomeMapper.updateLockStateByRoomNum(roomId, 0L);
                                    if (updateResult > 0) {
                                        log.info("房间 {} 的 lock_state 已更新为 0", roomId);
                                    } else {
                                        log.warn("房间 {} 的 lock_state 更新失败", roomId);
                                    }
                                } else {
                                    log.info("房间 {} 的 lock_state 不为 1，当前值: {}", roomId, roomInfo.getLockState());
                                }
                            } else {
                                log.warn("未找到房间编号为 {} 的房间信息", roomId);
                            }
                        } catch (Exception e) {
                            log.error("检查房间 lock_state 或自动开门时发生异常", e);
                        }
                    }
                }
                // 新增：处理开门日志 logType=4
                if (data != null && data.getIntValue("logType") == 4) {
                    JSONArray logKeys = data.getJSONArray("logKeys");
                    String roomId = data.getString("roomId");
                    String logId = data.getString("logId");
                    String remark = data.getString("logAlert");
                    if (logKeys != null && logKeys.size() > 0) {
                        JSONObject keyObj = logKeys.getJSONObject(0);
                        String lockKeyId = keyObj.getString("lockKeyId");
                        String type = String.valueOf(keyObj.getIntValue("keyType"));
                        if (lockKeyId != null) {
                            log.info("logType=4, 用户开的门, lockKeyId={}", lockKeyId);
                            log.info("开门详情: {}", com.alibaba.fastjson.JSONObject.toJSONString(data));
                            lockApiService.processOpenLog(roomId, type, logId, lockKeyId, remark);
                        }
                        else {
                            log.info("logType=4, 系统开的门");
                            log.info("系统开门详情: {}", com.alibaba.fastjson.JSONObject.toJSONString(data));
                            lockApiService.processOpenLog(roomId, type, logId, null, remark);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.warn("回调解析keyId/lockKeyId异常: {}", e.getMessage());
        }


        ack.acknowledge();

    }
}
